import websiteConfg from '@/util/config'
import rootRoter from '@/router/views'
import cloneDeep from 'lodash/cloneDeep'
const RouterPlugin = function () {
    this.$router = null
}
RouterPlugin.install = function (router) {
    this.$router = router
    this.$router.$asyncRouter = {
        safe: this,
        routerList: [],
        rootRoter:cloneDeep(rootRoter[0]),
        // 动态路由
        formatRoutes: function (aMenu = []) {
            const aRouter = []
            const propsConfig = websiteConfg.menuProps
            const propsDefault = {
                label: propsConfig.label || 'label',
                path: propsConfig.path || 'path',
                icon: propsConfig.icon || 'icon',
                children: propsConfig.children || 'children',
                meta: propsConfig.meta || 'meta'
            }
            if (aMenu.length === 0) return
            for (let i = 0; i < aMenu.length; i++) {
                const oMenu = aMenu[i]
                if (this.routerList.includes(oMenu[propsDefault.path])) return
                const path = (() => {
                    if (!oMenu[propsDefault.path]) {
                        return ''
                    } else {
                        return oMenu[propsDefault.path]
                    }
                })()
                //特殊处理组件
                const component = 'views' + oMenu.path
                const name = oMenu[propsDefault.label]
                const icon = oMenu[propsDefault.icon]
                const meta = oMenu[propsDefault.meta] || {}
                const oRouter = {
                    path: path,
                    component(resolve) {
                        require([`../${component}.vue`], resolve)
                    },
                    name: name,
                    icon: icon,
                    meta: meta,
                    redirect:oMenu.redirect || '',
                }
                this.rootRoter.children.push(oRouter)
            }
            if(!this.routerList.includes(this.rootRoter[propsDefault.path])){
                this.routerList.push(this.rootRoter[propsDefault.path])
                this.safe.$router.addRoutes([this.rootRoter])
            }else {
                return this.rootRoter
            }
        }
    }
}
export default RouterPlugin
